package net.hn.hnms.sys.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.mybatis.core.page.TableDataInfo;
import net.hn.hnms.sys.system.api.domain.SysLogininfor;
import net.hn.hnms.sys.system.mapper.SysLogininforMapper;
import net.hn.hnms.sys.system.service.ISysLogininforService;
import net.hn.hnms.sys.system.utils.OweDateUtils;
import net.hn.hnms.sys.system.vo.LoginInfoAnalysis;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author ruoyi
 */
@RequiredArgsConstructor
@Service
public class SysLogininforServiceImpl implements ISysLogininforService {

    private final SysLogininforMapper baseMapper;

    @Override
    public TableDataInfo<SysLogininfor> selectPageLogininforList(SysLogininfor logininfor, PageQuery pageQuery) {
        Map<String, Object> params = logininfor.getParams();
        LambdaQueryWrapper<SysLogininfor> lqw = new LambdaQueryWrapper<SysLogininfor>()
                .like(StringUtils.isNotBlank(logininfor.getIpaddr()), SysLogininfor::getIpaddr, logininfor.getIpaddr())
                .eq(StringUtils.isNotBlank(logininfor.getStatus()), SysLogininfor::getStatus, logininfor.getStatus())
                .like(StringUtils.isNotBlank(logininfor.getUserName()), SysLogininfor::getUserName, logininfor.getUserName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysLogininfor::getAccessTime, params.get("beginTime"), params.get("endTime"));
        if (StringUtils.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("info_id");
            pageQuery.setIsAsc("desc");
        }
        Page<SysLogininfor> page = baseMapper.selectPage(pageQuery.build(), lqw);
        List<SysLogininfor> list = page.getRecords();
        list.forEach(l -> {
            l.setAccessTime(addHours(l.getAccessTime(), 8));
        });
        return TableDataInfo.build(page);
    }

    public static Date addHours(Date date, int hours) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, hours);
        return calendar.getTime();
    }

    /**
     * 新增系统登录日志
     *
     * @param logininfor 访问日志对象
     */
    @Override
    public int insertLogininfor(SysLogininfor logininfor) {
        logininfor.setAccessTime(new Timestamp(new Date().getTime()));
        return baseMapper.insert(logininfor);
    }

    /**
     * 查询系统登录日志集合
     *
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininfor> selectLogininforList(SysLogininfor logininfor) {
        Map<String, Object> params = logininfor.getParams();
        List<SysLogininfor> sysLogininfors = baseMapper.selectList(new LambdaQueryWrapper<SysLogininfor>()
                .like(StringUtils.isNotBlank(logininfor.getIpaddr()), SysLogininfor::getIpaddr, logininfor.getIpaddr())
                .eq(StringUtils.isNotBlank(logininfor.getStatus()), SysLogininfor::getStatus, logininfor.getStatus())
                .like(StringUtils.isNotBlank(logininfor.getUserName()), SysLogininfor::getUserName, logininfor.getUserName())
//            .between(params.get("beginTime") != null && params.get("endTime") != null,
//                SysLogininfor::getAccessTime, params.get("beginTime"), params.get("endTime"))
                .orderByDesc(SysLogininfor::getInfoId));
        return sysLogininfors;
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return 结果
     */
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        return baseMapper.deleteBatchIds(Arrays.asList(infoIds));
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor() {
        baseMapper.delete(new LambdaQueryWrapper<>());
    }

    @Override
    public List<LoginInfoAnalysis> getLoginInfoAnalysis(String searchDate) {
        List<LoginInfoAnalysis> result = new ArrayList<>();
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 解析传入的日期字符串为 LocalDate 对象（默认设置为该月的第一天）
        DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate firstDayOfMonth = LocalDate.parse(searchDate + "-01", DateTimeFormatter.ISO_LOCAL_DATE);
        String startDate = firstDayOfMonth.format(dayFormatter);
        String endDate = firstDayOfMonth.with(TemporalAdjusters.lastDayOfMonth()).format(dayFormatter);
        // 判断是否为当前月份
        if (firstDayOfMonth.getYear() == today.getYear() && firstDayOfMonth.getMonth() == today.getMonth()) {
            // 如果是当前月份，返回今天的日期
            endDate = today.format(dayFormatter);
        }
        List<String> days = OweDateUtils.getXData(startDate, endDate, "day");
        List<LoginInfoAnalysis> loginInfoAnalysis = baseMapper.getLoginInfoAnalysis(startDate, endDate);
        for (String day : days) {
            LoginInfoAnalysis loginInfoAnalysis1 = loginInfoAnalysis.stream().filter(l -> l.getLoginDate().equals(day)).findFirst().orElse(new LoginInfoAnalysis(day, 0, 0));
            result.add(loginInfoAnalysis1);
        }
        return result;
    }
}
